package models

import (
	"fmt"
	"go-admin-official/modules/database"
)

type GoodsModel struct {
	Base `json:"-"`

	Id          int64  `json:"id"`
	Uuid        string `json:"uuid"`
	UserId      int64  `json:"user_id"`
	ProductId   int64  `json:"product_id"`
	Type        int64  `json:"type"`
	ProductType int64  `json:"product_type"`
	Description string `json:"description"`
	Price       int64  `json:"price"`
	Discount    int64  `json:"discount"`
	State       int64  `json:"state"`
	Title       string `json:"title"`
	CreatedAt   string `json:"created_at"`
	UpdatedAt   string `json:"updated_at"`
}

func Goods() GoodsModel {
	return GoodsModel{Base: Base{Table: "goods"}}
}

func (t GoodsModel) WithTx(tx *database.SqlTx) GoodsModel {
	t.Tx = tx
	return t
}

func (t GoodsModel) PriceStr() string {
	return fmt.Sprintf("%.2f", float64(t.Price)/100)
}

func (t GoodsModel) Find(id interface{}) GoodsModel {
	item, _ := database.Table(t.Table).Find(id)

	if item == nil {
		return Goods()
	}

	return t.MapToModel(item)
}

func (t GoodsModel) IsPlugin() bool {
	return t.Type == int64(0)
}

func (t GoodsModel) IsTheme() bool {
	return t.Type == int64(1)
}

func (t GoodsModel) FindByUUID(uuid interface{}) (GoodsModel, error) {
	item, err := database.Table(t.Table).Where("uuid", "=", uuid).First()

	if item == nil || err != nil {
		return Goods(), err
	}

	return t.MapToModel(item), err
}

func (t GoodsModel) Update(key string, value interface{}) (int64, error) {
	return database.Table(t.Table).
		Where("id", "=", t.Id).
		Update(database.H{
			key: value,
		})
}

func (t GoodsModel) IsEmpty() bool {
	return t.Id == int64(0)
}

func (t GoodsModel) IsNotEmpty() bool {
	return t.Id != int64(0)
}

func (t GoodsModel) MapToModel(m map[string]interface{}) GoodsModel {
	t.Id, _ = m["id"].(int64)
	t.Uuid, _ = m["uuid"].(string)
	t.UserId, _ = m["user_id"].(int64)
	t.ProductId, _ = m["product_id"].(int64)
	t.Type, _ = m["type"].(int64)
	t.ProductType, _ = m["product_type"].(int64)
	t.Description, _ = m["description"].(string)
	t.Price, _ = m["price"].(int64)
	t.Discount, _ = m["discount"].(int64)
	t.State, _ = m["state"].(int64)
	t.Title, _ = m["title"].(string)
	t.CreatedAt, _ = m["created_at"].(string)
	t.UpdatedAt, _ = m["updated_at"].(string)
	return t
}
